import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../../../beans/transcript_item_model.dart';
import '../../../db/DbDAOHelper.dart';
import '../../../utils/tips.dart';
import '../../../views/controller/RecordTranscriptViewRecordingController.dart';

class EditScriptlistController extends GetxController {

  RxList<AudioTranscriptDataExtends> audioTranscriptSource = RxList<AudioTranscriptDataExtends>();
  var script_edit_mode = false.obs;
  final scriptController = TextEditingController();

  TranscriptItem? currentTmpTranscriptItem;
  String? sessionId;
  var hasTranScript = false.obs;

  @override
  void onInit() {
    super.onInit();

    sessionId = Get.parameters['sessionId'];

    loadData();

  }

  void loadData() {
    currentTmpTranscriptItem = TranscriptItem();

    DbDAOHelper().obtainSessionBySessionId(int.parse(sessionId!)).then((sessions) {

      if (sessions.isNotEmpty) {
        //查询转写脚本.
        DbDAOHelper().obtainTranscriptsBySessionId(int.parse(sessionId!)).then((transcripts) {
          transcripts.forEach((scriptData) {
            AudioTranscriptDataExtends audioExtends = AudioTranscriptDataExtends(id: scriptData.id, session_id: scriptData.session_id,
                chat_sequence: scriptData.chat_sequence,
                m_id: scriptData.m_id,
                a_text: scriptData.a_text,
                duration: scriptData.duration,
                offset: scriptData.offset,
                speaker: scriptData.speaker,
                create_time: scriptData.create_time,
                update_time: scriptData.update_time);

            audioExtends.textEditingController.text = scriptData.a_text;
            audioTranscriptSource.add(audioExtends);
          });

          if (audioTranscriptSource.isEmpty) {
            hasTranScript.value = false;
          } else {
            hasTranScript.value = true;
          }

        });
      }
    });

  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void saveBatches() {
    if(audioTranscriptSource.value.isEmpty) {
      Tips.showToast('暂无数据.');
      return;
    }

    audioTranscriptSource.value.forEach((item) {
       int transcriptItemId =  item.id;
       DbDAOHelper().updateRecordsTranscript(transcriptItemId, item.textEditingController.text);
    });

    RecordTranscriptViewRecordingController recordTranscriptViewRecordingController =
    Get.find<RecordTranscriptViewRecordingController>();

    recordTranscriptViewRecordingController.reloadData();


  }



}
